//
//  moreLabxController.m
//  SoundPill
//
//  Created by 宋旭东 on 16/5/27.
//  Copyright © 2016年 宋旭东. All rights reserved.
//

#import "moreLabxController.h"

#import "playerTableViewController.h"
#import "Find_Activity_Model.h"
#import "Find_ActivityTableViewCell.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "JCAlertView.h"
#import "UIImageView+WebCache.h"
#import "UIViewController+MMDrawerController.h"
typedef enum {
    NETWORK_state_NONE= 0,
    NETWORK_state_2G= 1,
    NETWORK_state_3G= 2,
    NETWORK_state_4G= 3,
    NETWORK_state_5G= 4,//  5G目前为猜测结果
    NETWORK_state_WIFI= 5,
}NETWORK_state;

@interface moreLabxController ()<UITableViewDelegate, UITableViewDataSource, MJRefreshBaseViewDelegate>
{
    int page;
    int lastPage;
    int pages;
    NSString *_filePath;
    MJRefreshHeaderView *header;
    MJRefreshFooterView *fotter;
}
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UITableView *ActivityTableView;
@property (strong, nonatomic) NSMutableArray *activityArray;
@property (assign, nonatomic) NSInteger type;
@end

@implementation moreLabxController
- (instancetype)initWithTypeid:(NSString *)type_id
{
    self = [super init];
    if (self) {
        self.activityArray = [NSMutableArray array];
        self.hidesBottomBarWhenPushed = YES;
        _type = type_id.integerValue;
    }
    return self;
}
- (void)viewDidLoad
{
    
    
    
    [super viewDidLoad];
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    _titleLabel.textColor = [UIColor blackColor];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.navigationItem.titleView = _titleLabel;
    switch (_type) {
        case 1:
            _titleLabel.text = @"唱片";
            break;
        case 2:
            _titleLabel.text = @"周边";
            break;
        case 3:
            _titleLabel.text = @"线下活动";
            break;
        case 4:
            _titleLabel.text = @"生活方式";
            break;
        default:
            break;
    }

    UIButton *seaechItem = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [seaechItem setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    [seaechItem addTarget:self action:@selector(leftItemClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:seaechItem];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.view.backgroundColor = [UIColor whiteColor];
    [self createTableView];
    [header beginRefreshing];
}
- (void)leftItemClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)createTableView
{
    self.ActivityTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64) style:UITableViewStylePlain];
    //    _ActivityTableView.backgroundColor = [UIColor blueColor];
    _ActivityTableView.delegate = self;
    _ActivityTableView.dataSource = self;
    _ActivityTableView.showsVerticalScrollIndicator = NO;
    _ActivityTableView.showsHorizontalScrollIndicator = NO;

    _ActivityTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_ActivityTableView];
    
    if ([self.ActivityTableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.ActivityTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.ActivityTableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.ActivityTableView setLayoutMargins:UIEdgeInsetsZero];
    }
    //刷新控件
    header = [MJRefreshHeaderView header];
    header.scrollView = _ActivityTableView;
    header.delegate = self;
    fotter = [MJRefreshFooterView footer];
    fotter.scrollView = _ActivityTableView;
    fotter.delegate = self;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _activityArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return tableView.frame.size.height / 3.7;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        static NSString *ActivityTableIdentifer = @"activity";
        Find_ActivityTableViewCell *activityCell = [tableView dequeueReusableCellWithIdentifier:ActivityTableIdentifer];
        if (activityCell == nil) {
            activityCell = [[Find_ActivityTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ActivityTableIdentifer];
            activityCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (_activityArray.count > 0) {
            __weak Find_ActivityTableViewCell *cell = activityCell;
            Find_Activity_Model *model = _activityArray[indexPath.row];
            [activityCell.bigImage setImageWithURL:[NSURL URLWithString:model.cover] placeholderImage:[UIImage imageNamed:@"plazz_placeholderImage"] options:SDWebImageRetryFailed progress:^(NSUInteger receivedSize, long long expectedSize) {
                cell.imageProgress.hidden = NO;
                cell.imageProgress.progress = receivedSize / (float)expectedSize;
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    cell.imageProgress.hidden = YES;
                });
            }];
            activityCell.workName.text = model.title;
            if (model.price.floatValue == 0.0) {
                activityCell.price.text = @"免费";
            } else {
                activityCell.price.text = [NSString stringWithFormat:@"¥%d",[model.price intValue]];
            }
            activityCell.workCreateTime.text = [model.comptime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
            activityCell.playLab.text = model.play_count;
            activityCell.loveLab.text = model.love_count;
            activityCell.typeLable.text = model.type_name;
            //        NSLog(@"%@",activityCell.workCreateTime.text);
            
        }
        return activityCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    Find_Activity_Model *model = _activityArray[indexPath.row];
    NSString *workid = model.id;
    [self gotoPlayer:workid];
}
- (void)gotoPlayer:(NSString *)workid
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *isPlay = [userDefaults objectForKey:@"isWiFiPlay"];
    NSString *pppp=[NSString stringWithFormat:@"%u",[self getNetworkTypeFromStatusBar]];
    
    if (([isPlay isEqualToString:@"1"]&&[pppp isEqualToString:@"5"])||[pppp isEqualToString:@"5"]||([isPlay isEqualToString:@"0"]&&![pppp isEqualToString:@"0"])||isPlay==nil) {
        NSString *CinemeID = workid;
        Player_ShowModel *playModel = [Player_ShowModel sharedInstance];
        
        UINavigationController *nv = (UINavigationController *)self.mm_drawerController.rightDrawerViewController;
        playerTableViewController *player = (playerTableViewController *)nv.topViewController;
        NSString *showURL = [NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/show", CinemeID];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
        [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
        [manager GET:showURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSDictionary *dataDic = [dic valueForKey:@"data"];
            NSDictionary *linksDic = [dic valueForKey:@"links"];
            [playModel setValuesForKeysWithDictionary:dataDic];
            if ([[dic allKeys] containsObject:@"meta"]) {
                NSDictionary *meta = [dic valueForKey:@"meta"];
                NSString *userAvatar = [meta valueForKey:@"userAvatar"];
                player.locUserAvatar = userAvatar;
//                NSArray *array = [meta valueForKey:@"playlist"];
//                player.playList = [NSMutableArray arrayWithArray:array]
                ;
                playModel.comment_count = [meta valueForKey:@"count"];
                ;
            }
            player.waveform = [linksDic valueForKey:@"waveform"];
            player.workID = CinemeID;
            player.isSelf = NO;
            //        if (isCinemeIDPlay == NO) {
            [player reloadViews:playModel];
            //        }
            [self.mm_drawerController toggleDrawerSide:MMDrawerSideRight animated:YES completion:^(BOOL finished) {
            }];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    } else {
        [JCAlertView showOneButtonWithTitle:@"你已开启仅Wifi环境播放" Message:@"可以去设置关闭此功能" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
            
        }];
        
    }
}
-(NETWORK_state)getNetworkTypeFromStatusBar {
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];
    NSNumber *dataNetworkItemView = nil;
    for (id subview in subviews) {
        if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]])     {
            dataNetworkItemView = subview;
            break;
        }
    }
    NETWORK_state nettype = NETWORK_state_NONE;
    NSNumber * num = [dataNetworkItemView valueForKey:@"dataNetworkType"];
    nettype = [num intValue];
    return nettype;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        fotter.hidden = NO;
        [_activityArray removeAllObjects];
        [self AFNetworking:page refreshing:refreshView];
    }else { // 上拉加载更多
        if (pages == 1 || page == pages) {
            fotter.hidden = YES;
        } else {
            page++;
            [self AFNetworking:page refreshing:refreshView];
        }
    }
}
- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    
}
- (void)AFNetworking:(int)pag refreshing:(MJRefreshBaseView *)refreshView
{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/work/discover?p=%d&type=%d", pag,_type];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self reloadActivityData:responseObject pag:pag];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [refreshView endRefreshing];
        });
        if (pag == 1) {
            //            BOOL result =
            //            [operation.responseData writeToFile:_filePath atomically:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [refreshView endRefreshing];
    }];
    
}
- (void)reloadActivityData:(id)responseObject pag:(int)pag
{
    NSDictionary *bigDic = responseObject;
    NSDictionary *dic = [bigDic valueForKey:@"data"];
    for (NSDictionary *dict in dic) {
        Find_Activity_Model *model = [[Find_Activity_Model alloc] init];
        [model setValuesForKeysWithDictionary:dict];
        [_activityArray addObject:model];
    }
    NSDictionary *meta = [bigDic valueForKey:@"meta"];
    if (meta != nil) {
        pages = [[meta valueForKey:@"pages"] intValue];
        if (pages == 1 || pag == pages) {
            fotter.hidden = YES;
        }
    }
    [_ActivityTableView reloadData];
}
@end
